# !/usr/bin/env python3
# coding=utf8
"""
从"通达信"导出"主力期货合约"的数据, 脚本载入数据, 生成 json 文件, 供人工查阅,

导出的步骤:
1. (最顶部的左侧的)行情=>(从底部的Tab里找到)期货现货=>主力期货合约
2. (最顶部的右侧的)选项=>数据导出
3. 格式文本文件=>所有数据(显示列开始所有栏目)=>导出
4. 得到文件: C:/new_tdx/T0002/export/主力期货合约20250507.txt
"""
import csv
import json
import pathlib
from typing import Any, Type, Optional, Union, Callable, Sequence  # , Dict, List, Set, Tuple
import vnpy.tools.utility


def load_file(filepath: Union[str, pathlib.Path]) -> list[dict]:
    """"""
    lines: list[dict] = []

    with open(file=filepath, mode='r', encoding='gbk', newline='') as f:
        csvReader = csv.DictReader(f, dialect='excel', delimiter='\t')

        for row in csvReader:
            if row['代码'] == '数据来源:通达信':  # 数据读取完了,
                break

            row = {k.strip(): v.strip() for k, v in row.items()}

            line: dict = {
                "exchange": vnpy.tools.utility.get_exchange(row['代码']).value,
                "product": vnpy.tools.utility.get_product(row['代码']),
                "example": f"{row['代码']},{row['名称']}",
                "name": row['名称'],
                "multiple": row['每手乘数'],
                "price_tick": float(row['最小变动价']),
                "lclose": float(row['昨收盘价']),
                "lsettle": float(row['昨结算价']),
                "volume": float(row['总量']),
                "notional_value": float(row['昨结算价']) * float(row['每手乘数'].split('_')[0]),  # 名义价值,
            }
            lines.append(line)

    return lines


if __name__ == "__main__":
    filepath: str = r"C:\new_tdx\T0002\export\主力期货合约20250507.txt"

    lines: list[dict] = load_file(filepath=filepath)

    # 按"notional_value"(名义价值)从小到大排序,
    lines.sort(key=lambda _: _["notional_value"], reverse=False)

    destpath: str = __file__ + ".notional_value.json"

    with open(file=destpath, mode="w", encoding="utf8") as f:
        json.dump(obj=lines, fp=f, ensure_ascii=False, indent=4)

    print("DONE", destpath)
